package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.IWechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author zgp
 * @version V1.0
 * @date 2025-03-03 17:08
 */
@Service
public class WechatServiceImpl implements IWechatService {
    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    /**
     * 根据临时凭证code获取唯一凭证
     *
     * @param code 用户临时凭证code
     * @return openId
     */
    @Override
    public String getOpenId(String code) {
        // 调用微信登录接口
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("js_code", code);
        String result = HttpUtil.get(REQUEST_URL, params);
        if(StrUtil.isNotEmpty(result)){
            // 解析JSON
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if(ObjUtil.isNotNull(jsonObject) && (ObjectUtil.isNull(jsonObject.get("errcode")) || Integer.valueOf(0).equals(jsonObject.get("errcode")))){
                return jsonObject.get("openid").toString();
            }
        }
        throw new BaseException("登录失败");
    }

    /**
     * 根据手机号获取凭证换取手机号
     *
     * @param detailCode code凭证
     * @return phoneNumber
     */
    @Override
    public String getPhoneNumber(String detailCode) {
        // 获取access_token
        String token = getAccessToken();
        // 获取用户登录手机号
        Map<String, Object> params = new HashMap<>();
        params.put("code", detailCode);
        String result = HttpUtil.post(PHONE_REQUEST_URL + token, JSONUtil.toJsonStr(params));
        if(ObjUtil.isNotNull(result)){
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if(ObjUtil.isNotNull(jsonObject) && ObjUtil.equals(jsonObject.get("errcode"), 0)){
                return JSONUtil.parseObj(jsonObject.get("phone_info")).get("phoneNumber").toString();
            }
        }
       throw new BaseException("获取phoneNumber失败");
    }

    /**
     * 获取access_token
     * @return access_token
     */
    private String getAccessToken() {
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        String result = HttpUtil.get(TOKEN_URL, params);
        if(ObjUtil.isNotNull(result)){
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if(ObjUtil.isNotNull(jsonObject) && ObjUtil.isNotNull(jsonObject.get("access_token"))){
                return jsonObject.get("access_token").toString();
            }
        }
        throw new BaseException("获取access_token失败");
    }
}
